import { defineStore } from 'pinia'
import {
  listAllPermissionsAPI,
  addPermissionAPI,
  updatePermissionAPI,
  deletePermissionAPI,
  getPermissionByIdAPI,
  togglePermissionStatusAPI,
  searchByPermissionNameAPI
} from '@/api/permisssionAPI'

export const usePermissionStore = defineStore('permission', {
  state: () => ({
    permissions: [],
    total: 0,
    currentPage: 1,
    pageSize: 10,
    loading: false,
    selectedPermission: null
  }),

  actions: {
    // 获取所有权限（带分页）
    async fetchPermissions(page = 1, size = 10) {
      this.loading = true
      try {
        const res = await listAllPermissionsAPI({
          pageNo: page,
          pageSize: size
        })

        // 修改判断条件以适配后端返回的 code: 0 表示成功
        if (res && (res.code === 0 || res.code === 200) && res.data) {
          // 处理 MyBatis Plus 分页返回的数据结构
          // 后端返回的是 Page<SysPermissionVO> 对象，包含 records 和 total 字段
          if (res.data && Array.isArray(res.data.records)) {
            this.permissions = res.data.records
            this.total = res.data.total || 0
          } else {
            // 如果没有 records 字段或不是数组，则初始化为空
            this.permissions = []
            this.total = 0
          }

          this.currentPage = page
          this.pageSize = size
        } else {
          console.error('获取权限列表失败:', res?.message || '未知错误')
          this.permissions = []
          this.total = 0
        }
      } catch (error) {
        console.error('获取权限失败:', error)
        this.permissions = []
        this.total = 0
      } finally {
        this.loading = false
      }
    },

    // 根据权限名搜索权限
    async searchPermissionsByPermissionName(permissionName, page = 1, size = 10) {
      this.loading = true
      try {
        const res = await searchByPermissionNameAPI({
          permissionName: permissionName || undefined
        })

        if (res && (res.code === 0 || res.code === 200) && res.data) {
          // 处理返回的数据
          if (Array.isArray(res.data)) {
            this.permissions = res.data
            this.total = res.data.length
          } else {
            this.permissions = []
            this.total = 0
          }

          this.currentPage = page
          this.pageSize = size
          return { success: true }
        } else {
          console.error('搜索权限失败:', res?.message || '未知错误')
          this.permissions = []
          this.total = 0
          throw new Error(res?.message || '搜索权限失败')
        }
      } catch (error) {
        console.error('搜索权限失败:', error)
        this.permissions = []
        this.total = 0
        throw error
      } finally {
        this.loading = false
      }
    },

    // 新增权限
    async addPermission(permissionData) {
      try {
        const res = await addPermissionAPI(permissionData)
        if (res && (res.code === 0 || res.code === 200)) {
          await this.fetchPermissions(this.currentPage, this.pageSize)
          return { success: true }
        } else {
          throw new Error(res?.message || '添加权限失败')
        }
      } catch (error) {
        console.error('新增权限失败:', error)
        throw error
      }
    },

    // 编辑权限
    async updatePermission(id, permissionData) {
      try {
        const res = await updatePermissionAPI({
          id: id,
          saveBO: permissionData
        })

        if (res && (res.code === 0 || res.code === 200)) {
          await this.fetchPermissions(this.currentPage, this.pageSize)
          return { success: true }
        } else {
          throw new Error(res?.message || '更新权限失败')
        }
      } catch (error) {
        console.error('更新权限失败:', error)
        throw error
      }
    },

    // 删除权限
    async deletePermission(id) {
      try {
        const res = await deletePermissionAPI(id)
        if (res && (res.code === 0 || res.code === 200)) {
          await this.fetchPermissions(this.currentPage, this.pageSize)
          return { success: true }
        } else {
          throw new Error(res?.message || '删除权限失败')
        }
      } catch (error) {
        console.error('删除权限失败:', error)
        throw error
      }
    },

    // 获取单个权限详情
    async getPermissionById(id) {
      try {
        const res = await getPermissionByIdAPI(id)
        if (res && (res.code === 0 || res.code === 200) && res.data) {
          this.selectedPermission = res.data
          return res.data
        } else {
          throw new Error(res?.message || '获取权限详情失败')
        }
      } catch (error) {
        console.error('获取权限详情失败:', error)
        throw error
      }
    },

    // 切换权限状态
    async togglePermissionStatus(id) {
      try {
        const res = await togglePermissionStatusAPI(id)
        if (res && (res.code === 0 || res.code === 200)) {
          await this.fetchPermissions(this.currentPage, this.pageSize)
          return { success: true }
        } else {
          throw new Error(res?.message || '切换权限状态失败')
        }
      } catch (error) {
        console.error('切换权限状态失败:', error)
        throw error
      }
    }
  }
})
